package com.qf.shop.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.qf.shop.auth.feign.api.CarService;
import com.qf.shop.auth.feign.api.UserService;
import com.qf.shop.common.constants.AuthConstants;
import com.qf.shop.common.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthBaiduRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 实现第三登录
@Controller
@Slf4j
@RequestMapping("/oauth")
public class RestOAuthLogin {

    @Autowired
    private UserService userService;

    @Autowired
    private CarService carService;

    @RequestMapping("/login")
    public void login(HttpServletResponse response) throws IOException {
        log.debug("进入login");

        // 1.获取应用的信息(id，重定向的url)
        AuthRequest authRequest = getAuthRequest();

        // 2.获取引导应用授权的地址
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        log.debug("authorizeUrl:{}", authorizeUrl);

        // 3.重定向到授权页面
        response.sendRedirect(authorizeUrl);
    }

    @RequestMapping("/callback")
    public String callback(AuthCallback callback, HttpServletRequest request) {
        log.debug("进入callback：callback params：" + JSONObject.toJSONString(callback));

        // 1.获取应用的信息
        AuthRequest authRequest = getAuthRequest();

        // 2.登录(根据Code获取AccessToken，根据AccessToken获取用户的信息)
        AuthResponse<AuthUser> response = authRequest.login(callback);

        log.debug(JSONObject.toJSONString(response));

        // 3.判断是否登录成功
        if (response.ok()) {
            log.debug("登录成功。。。");

            AuthUser data = response.getData();


            // 2.查询这个第三方用户是否是第一次登录
            UserVo userVo = userService.findUser("oauth_id", data.getUuid());

            if (userVo == null) {
                // 封装第三方登录的用户
                userVo = new UserVo();
                userVo.setUsername(data.getUsername());
                userVo.setOauthId(data.getUuid());


                // 第一次登录把第三方用户注册一下
                userService.register(userVo); //username,oauth_id

                userVo = userService.findUser("oauth_id", data.getUuid());
            }
            log.debug("userVO:{}", userVo);
            // 把当前登录的用户放到session中
            request.getSession().setAttribute(AuthConstants.LOGIN_USER, userVo);

            // 合并购物车
            carService.mergeCar(userVo.getId());


            // 跳转到首页
            return "redirect:http://localhost/home";
        }
        return "redirect:http://localhost/auth/loginUser.html?error=xxxxx";
    }

    private AuthRequest getAuthRequest() {
        return new AuthBaiduRequest(AuthConfig.builder()
                .clientId("4Dm8L6L5OFiPjoKF8oLOUG9u")
                .clientSecret("8dN0bzkYsrMWs1EDABXYv6eTg67GESTh")
                .redirectUri("http://localhost/oauth/callback")
                .build());

//        return new AuthWeiboRequest(AuthConfig.builder()
//                .clientId("654865914")
//                .clientSecret("a742df7a73eacf3a6b2dddf51acb6bd9")
//                .redirectUri("http://www.localhost/oauth/callback")
//                .scopes(Arrays.asList(
//                        AuthWeiboScope.EMAIL.getScope(),
//                        AuthWeiboScope.FRIENDSHIPS_GROUPS_READ.getScope(),
//                        AuthWeiboScope.STATUSES_TO_ME_READ.getScope()
//                ))
//                .build());
    }
}
